import os
import sys
import glob
import numpy as np


def bais2(basedir):
    """
    #param basedir 存放哨兵2的L2级产品的文件夹
    """
    #找出每景哨兵影像
    s2_folders = [item for item in os.listdir(basedir) 
                if not os.path.basename(item).endswith('BIAS')]

    beta = 1e-4
    #遍历找到每一景大气校正后分辨率20米的文件夹
    for s2_folder in s2_folders:
        B4_20m = glob.glob('{}\\{}\\**\\*B04_20m.jp2'.format(basedir, s2_folder), recursive=True)[0]
        B4_20m_f = "{}\\BIAS\\floattmp\\{}_float.jp2".format(basedir, os.path.split(B4_20m)[1][:-4])
        B6_20m = glob.glob('{}\\{}\\**\\*B06_20m.jp2'.format(basedir, s2_folder), recursive=True)[0]
        B7_20m = glob.glob('{}\\{}\\**\\*B07_20m.jp2'.format(basedir, s2_folder), recursive=True)[0]
        B8a_20m = glob.glob('{}\\{}\\**\\*B8A_20m.jp2'.format(basedir, s2_folder), recursive=True)[0]
        B12_20m = glob.glob('{}\\{}\\**\\*B12_20m.jp2'.format(basedir, s2_folder), recursive=True)[0]
        # B8_20m = glob.glob('{}\\{}\\**\\*B08_20m.jp2'.format(basedir, s2_folder), recursive=True)[0]

        cmd1 = "gdal_translate -ot Float32 {} {}".format(B4_20m, B4_20m_f)
        os.system(cmd1)
        CMD = 'python P:\\AoiSoft\\ANACONDA\\Scripts\\gdal_calc.py' \
              ' -A {} -B {} -C {} -D {} -E {} --format=GTiff --outfile={}\\BIAS\\{}_bias2.tif ' \
              '--calc="(1-1.0*sqrt((1.0*B*C*D)/(1.0*A*1e8+1e-9)))*((1.0*E-1.0*D)/(1e2*sqrt(1.0*E+1.0*D+1e-9))+1)"'\
            .format(B4_20m_f, B6_20m, B7_20m, B8a_20m, B12_20m, basedir, s2_folder)
        # CMD = 'python P:\\AoiSoft\\ANACONDA\\Scripts\\gdal_calc.py -A {} -B {} --format=GTiff --outfile={}\\BIAS\\{}_NDVI.tif --calc="(B/10000.0 - A/10000.0 + 0.0001)/(B/10000.0 + A/10000.0 + 0.0001)"'.format(B4_20m, B8_20m, basedir, s2_folder)
        os.system(CMD)

    pass


if __name__ == "__main__":
    bais2("D:\\tmp")